#include <stdio.h>
#include <string.h>

#define MAX_LEN 10
int Judge(char *, int);
int ReadLine(char *s);

int ReadLine(char *s)
{
    int n = 0, ch = 0;
    while((ch = getchar()) != '\n' && ch != EOF && n <= MAX_LEN - 1)
        s[n++] = ch;
    s[n]='\0';
    return n;
}

int main()
{
    char str[MAX_LEN];
    int n;
    while(ReadLine(str) > 0){
        scanf("%d", &n);
        getchar();
        printf("%d\n", Judge(str, n));
    }
    return 0;
}

/* 限行判断函数 */
int Judge(char *plate_num, int day)
{
    int i, k;
    int len = strlen(plate_num);

    /* 车牌号长度或天的星期数不合法 */
    if((len != 5 && len != 6) || day < 1 || day > 7)
    {
        return -1;
    }

    /* 车牌含有非法字符 */
    for(i = 0; i < len; i++)
    {
        if(!(plate_num[i] >= '0' && plate_num[i] <= '9') &&
           !(plate_num[i] >= 'A' && plate_num[i] <= 'Z'))
        {
            return -1;
        }
    }

    /* 6位新能源车或是星期六或星期天不限行 */
    if(len == 6 || day >= 6)
    {
        return 0;
    }

    k = -1;
    /* 遍历车牌号字符串 */
    for(i = len - 1; i >= 0; i--)
    {
        /* 取得尾号的索引值 */
        if(plate_num[i] >= '0' && plate_num[i] <= '9')
        {
            if( k == -1 )
            {
                k = i;
            }
        }
    }

    /* 未发现数字字符 */
    if(k == -1)
    {
        return -1;
    }

    /* 将尾号转换为整数 */
    k = plate_num[k] - '0';
    /* 归一化为0-4之间的整数 */
    k %= 5;
    day %= 5;

    /* 判断是否为限行车牌号 */
    if(k == day)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
